package com.zjh.document.service.impl;

import com.jcraft.jsch.*;
import com.zjh.document.entity.DTO.FileInfo;
import com.zjh.document.entity.DTO.ServerConfig;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

@Service
public class SftpService {
    private Session session;
    private ChannelSftp channelSftp;

    public void connect(ServerConfig config) throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(config.getUsername(), config.getHost(), config.getPort());
        session.setPassword(config.getPassword());
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();
        channelSftp = (ChannelSftp) channel;
    }

    public void disconnect() {
        if (channelSftp != null) {
            channelSftp.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }

    public List<FileInfo> listFiles(String path) throws SftpException {
        List<FileInfo> fileInfos = new ArrayList<>();
        Vector<ChannelSftp.LsEntry> files = channelSftp.ls(path);

        for (ChannelSftp.LsEntry entry : files) {
            if (entry.getFilename().equals(".") || entry.getFilename().equals("..")) {
                continue;
            }

            FileInfo fileInfo = new FileInfo();
            fileInfo.setName(entry.getFilename());
            fileInfo.setDirectory(entry.getAttrs().isDir());
            fileInfo.setSize(entry.getAttrs().getSize());
            fileInfo.setModifyTime(String.valueOf(entry.getAttrs().getMTime()));
            fileInfos.add(fileInfo);
        }

        return fileInfos;
    }

    public byte[] downloadFile(String filePath) throws SftpException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        channelSftp.get(filePath, outputStream);
        return outputStream.toByteArray();
    }

    public void uploadFile(String path, InputStream inputStream) throws SftpException {
        channelSftp.put(inputStream, path);
    }
}